package net.jltec.model.util;

import java.util.HashMap;
import java.util.Map;

import net.jltec.core.service.ICommonService;
import net.jltec.core.utils.Tools;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@SuppressWarnings("unchecked")
public class RequestContext {
	private final static ThreadLocal<Map> subs = new ThreadLocal<Map>();
	private final static ThreadLocal<Map> nodes = new ThreadLocal<Map>();
	
	
	/*appclient user logonid*/
	private final static ThreadLocal<Integer> applogonid = new ThreadLocal<Integer>();
	
	private static Log log = LogFactory.getLog(RequestContext.class);
	
	public final static void beginSubs(Map p) {
		try {
			String wtdcode =(String) ConvertUtils.convert(p.get("wtdcode"),String.class);
			if(StringUtils.isNotEmpty(wtdcode)){
				ICommonService service = Tools.getCommonService();
				if(service!=null){
					Map subParams = new HashMap();
					p.put("type", 1);//直接走子流程
					subParams = (Map) service.getJdao().query(p, "{call sp_workflow_sub_flow(#logonid:integer#,#type:integer#,#xml:varchar#)}");
					
					subs.set(subParams);
					
					Map nodeParams = new HashMap();
					p.put("type", 2);//按主流程配置跳转节点
					nodeParams = (Map) service.getJdao().query(p, "{call sp_workflow_sub_flow(#logonid:integer#,#type:integer#,#xml:varchar#)}");
					
					
					
					//如果为流程确认过来的会有nodeid 
					int nodeid =(Integer) ConvertUtils.convert(p.get("nodeid"),Integer.class);
					//确认流程页面标识
					int isckflow =(Integer) ConvertUtils.convert(p.get("isckflow"),Integer.class);
					if(nodeid>0 && isckflow==1){
						if(nodeParams==null){
							nodeParams = new HashMap();
						}
						nodeParams.put("nodeid", nodeid);
					}
					
					nodes.set(nodeParams);	
					
				}
			}
		} catch (Exception e) {
			log.error("beginSubs",e);
		}
		
		
	}
	
	public final static Map getSubParams(){
		Map p = subs.get();
		if(p==null){
			p = new HashMap();
		}
		return p;
	}
	
	public final static Map getNodeParams(){
		Map p = nodes.get();
		if(p==null){
			p = new HashMap();
		}
		return p;
	}
	
 
	
	public final static void beginAppLogonid(int logonid){
		applogonid.set(logonid);	
	}
	
	public final static int getAppLogonid(){
		return applogonid.get();
	}
	
	public final static void end(){
		subs.set(null);
		nodes.set(null);
		applogonid.set(null);
		 
	}
	
	
}
